package com.gdcp.controller.portal;

import com.gdcp.beans.RoleUser;
import com.gdcp.beans.Shop;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.config.security.CustomUserService;
import com.gdcp.config.security.validate.ImageCode;
import com.gdcp.service.*;
import com.gdcp.util.HttpServletRequestUtil;
import com.gdcp.util.ImageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/user/")
public class UserController {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    UserService userService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ShopService shopService;
    @Autowired
    CustomUserService customUserService;
    @Autowired
    RoleUserService roleUserService;

    @RequestMapping(value = "/login02",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(String username,String password){
        //HttpServletRequest request=RequestHolder.getRequest();
        //String username= HttpServletRequestUtil.getString(request,"username");
        //String password= HttpServletRequestUtil.getString(request,"password");

        if (username==null||username.equals("")){
            return responseModel.setModel(false,"用户名不能为空");
        }

        if (password==null||password.equals("")){
            return responseModel.setModel(false,"密码不能为空");
        }

        Map<String, Object> model = userService.login(username,password);
        Boolean b= (Boolean) model.get("success");
        if (b) {
            RequestHolder.setSession("user", model.get("message"));
        }
        //customUserService.loadUserByUsername(username);
        return model;
    }

    @RequestMapping(value = "/authentication",method = RequestMethod.GET)
    @ResponseBody
    public Authentication getCurrentUser(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> register(String username, String password, String imageCode){
        //HttpServletRequest request=RequestHolder.getRequest();
        ImageCode imageCodeSession= (ImageCode) RequestHolder.getSession("SESSION_KEY_IMAGE_CODE");
        //String username= HttpServletRequestUtil.getString(request,"");
        //String password= HttpServletRequestUtil.getString(request,"password");
        //String imageCodeText= HttpServletRequestUtil.getString(request,"imageCode");


        //System.out.println("imageCode.getCode()="+imageCode.getCode()+"text="+imageCodeText);
        if (imageCodeSession==null||imageCode.equals("")||!imageCodeSession.getCode().equals(imageCode)){
            return responseModel.setModel(false,"验证码错误");
        }
        if (username==null){
            return responseModel.setModel(false,"用户名不能为空");
        }
        if (password==null){
            return responseModel.setModel(false,"密码不能为空");
        }

        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        String image="\\upload\\images\\item\\shop\\81\\2019122222004223666.jpg";
        user.setImage(image);
        Map<String,Object> model=userService.register(user);
        return model;
    }

    @RequestMapping(value = "/update_userInfo",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateUserInfo(String old_password, String password, String username, String email,
                                             String phone,String question,String answer){
        //HttpServletRequest request=RequestHolder.getRequest();
        User user= (User) RequestHolder.getSession("user");

        //String old_password=HttpServletRequestUtil.getString(request,"old_password");

        if (old_password!=null&&!old_password.equals(user.getPassword())){
            return responseModel.setModel(false,"原密码错误");
        }

        //String password= HttpServletRequestUtil.getString(request,"password");
        if (password==null||password.equals("")){
            password=user.getPassword();
        }
        //String username= HttpServletRequestUtil.getString(request,"username");
        if (username==null||username.equals("")){
            username=user.getUsername();
        }
        //String email= HttpServletRequestUtil.getString(request,"email");
        if (email==null||email.equals("")){
            email=user.getEmail();
        }
        //String phone= HttpServletRequestUtil.getString(request,"phone");
        if (phone==null||phone.equals("")){
            phone=user.getPhone();
        }
        //String question= HttpServletRequestUtil.getString(request,"question");
        if (question==null||question.equals("")){
            question=user.getQuestion();
        }
        //String answer= HttpServletRequestUtil.getString(request,"answer");
        if (answer==null||answer.equals("")){
            answer=user.getAnswer();
        }

        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setQuestion(question);
        user.setAnswer(answer);
        Map<String,Object> model=userService.updateInformation(user);
        if (model.containsKey("success")){
            RequestHolder.setSession("user",user);
        }
        return model;
    }

    @RequestMapping(value = "/update_headPortrait")
    @ResponseBody
    public Map<String,Object> updateHeadPortrait(HttpServletRequest request){
        ImageDto headPortrait = null;
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 若请求中存在文件流，则取出相关的文件（包括缩略图和详情图）
        try{
            if(multipartResolver.isMultipart(request)){
                //获取文件流中图片信息
                headPortrait = handleImage(request);
            }
        }catch (Exception e){
            return responseModel.setModel(false,e.toString());
        }

        // 从session中获取当前店铺信息
        User currentUser = (User)RequestHolder.getSession("user");

        // 更新商品信息
        return userService.updateHeadPortrait(currentUser,headPortrait);
    }

    @RequestMapping(value = "exit")
    public Map<String,Object> exit(){
        RequestHolder.removeSession("user");
        return responseModel.setModel(true,"退出成功");
    }

    @RequestMapping(value = "registerShop",method = RequestMethod.GET)
    @Transactional(rollbackFor = { Exception.class })
    public String registerShop(){
        User user= (User) RequestHolder.getSession("user");
        //创建新的shop，默认数据有：user_id、create_time
        Shop shop=new Shop();
        shop.setUser_id(user.getId());
        shop.setShop_name(user.getId()+"的店铺");
        int count=shopService.registerShop(shop);
        if (count > 0){
            int shopCount=userService.updateShopId(shop.getId(),user.getId());
            if (shopCount<=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "redirect:/";
            }

            //前台就是直接插入
            //后台就分为两个情况（一个），如果插入的用户已存在那么就提示该用户已存在（报错）
            //判断是否为4，如果是的话，那么就直接插入，如果不是那么还要查询一次
            RoleUser roleUser=roleUserService.getInformationByUserId(user.getId());
            if (roleUser!=null&&roleUser.getIrole_id()==4){
                RoleUser roleUser1=new RoleUser();
                //System.out.println(roleUser);
                roleUser1.setId(roleUser.getId());
                roleUser1.setIuser_id(user.getId());
                roleUser1.setIrole_id(2);
                Map<String,Object> model=roleUserService.updateInformation(roleUser1);
                //User user1=userService.getInformation(user.getId());
                //RequestHolder.setSession("user",user1);
                if (!(Boolean) model.get("success")){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "redirect:/";
                }
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "redirect:/";
            }
        }

        return "redirect:/logout";
    }

    private ImageDto handleImage(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 取出缩略图并构建ImageHolder对象
        MultipartFile headPortraitFile = multipartRequest.getFile("headPortrait");
        ImageDto headPortrait=null;
        if (headPortraitFile != null) {
            headPortrait = new ImageDto(headPortraitFile.getOriginalFilename(), headPortraitFile.getInputStream());
        }

        return headPortrait;
    }
}